package com.sy.service.impl;


import com.sy.dto.CategoryNode;
import com.sy.dto.JsonResult;
import com.sy.entity.Category;
import com.sy.mapper.CategoryMapper;
import com.sy.service.CategoryService;
import com.sy.utils.HttpUtils;
import com.sy.utils.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.sy.constant.BusinessConstant.FIRST_LEVEL_CATEGORY_PARENT_ID;
import static com.sy.constant.BusinessConstant.REDIS_CATEGORY_KEY;

/**
 * 与博客类型相关的操作
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private HttpUtils httpUtils;

    @Override
    public JsonResult getAllCategoryNodes() {
        //从缓存中获取分类信息
        List<CategoryNode> categoryNodes;
        //1.如果有，直接返回
        if (redisClient.exists(REDIS_CATEGORY_KEY)) {
            System.out.println("从Redis获取...");
            categoryNodes = redisClient.getJsonObjList(REDIS_CATEGORY_KEY, CategoryNode.class);
        }
        //2.如果没有，从MySQL获取，并存入Redis，然后返回
        else {
            System.out.println("从MySQL获取...");
            //一级分类的节点信息
            List<CategoryNode> firstLevelCategoryNodes = new ArrayList<>();
            //先查询一级分类的信息
            List<Category> firstLevelCategories = categoryMapper.selectByParentId(FIRST_LEVEL_CATEGORY_PARENT_ID);
            for (Category firstLevelCategory : firstLevelCategories) {
                CategoryNode firstLevelCategoryNode = new CategoryNode();
                firstLevelCategoryNode.setCategory(firstLevelCategory);
                //在当前节点的下面添加其子节点信息，也就是二级分类的信息
                List<CategoryNode> secondLevelCategoryNodes = new ArrayList<>();
                //先查询二级分类的信息
                List<Category> secondLevelCategories = categoryMapper.selectByParentId(firstLevelCategory.getId());
                for (Category secondLevelCategory : secondLevelCategories) {
                    CategoryNode secondCategoryNode = new CategoryNode();
                    secondCategoryNode.setCategory(secondLevelCategory);
                    secondLevelCategoryNodes.add(secondCategoryNode);
                }
                firstLevelCategoryNode.setChildCategoryNodes(secondLevelCategoryNodes);
                firstLevelCategoryNodes.add(firstLevelCategoryNode);
            }
            categoryNodes = firstLevelCategoryNodes;
            redisClient.setJson(REDIS_CATEGORY_KEY, firstLevelCategoryNodes);
        }
        return httpUtils.buildSuccess(200,categoryNodes);
    }
}
